
#include <stdint.h>
//	#include "stm32f10x.h"
//	#include "stm32f10x_gpio.h"
//	#include "stm32f10x_tim.h"
#include "contract.h"
#include "clock_countor.h"
#include "ClockAlarmer.h"
#include "base.h"


static volatile uint32_t etu_timer_fraction = 8;
static volatile uint8_t etu_timeout_flag = 0;
static volatile uint8_t etu_alarm_flag = 0;

void timeout_action(void)
{
	etu_timeout_flag = 1;
}


void alarm_action(void)
{
	etu_alarm_flag = 1;
}

void ETUTimer_Init(uint32_t frequency)
{
	ClockCountor_Init(frequency);
	ClockAlarmer_Init(frequency);
}

uint32_t etu_to_clock(uint32_t etu, uint8_t FiDi)
{
	uint32_t F, D;
	uint32_t clock;
	
	F = convert_fi_code_to_value(FiDi >> 4);
	D = convert_di_code_to_value(FiDi & 0x0F);

	if( F == 0 || D == 0)
	{
		return 0;
	}
	//clock = etu * F * etu_timer_fraction / D;
	clock = 2*etu*F/D; /*ClockTimer 的实际时钟频率为72MHz*/
	return clock;
}

void ETUTimer_SetFrequency(uint32_t frequency)
{
	ClockCountor_SetCardClockFrequency(frequency);
	ClockAlarmer_SetCardClockFrequency(frequency);
	//etu_timer_fraction = ClockCountor_GetFrequency() / frequency;	
}

void ETUTimer_SetCountMultiple(uint32_t multiple)
{
	ClockCountor_SetCountMultiple(multiple);
}

void ETUTimer_Start(uint32_t etu, uint8_t FiDi)
{	
	uint32_t clock;

	clock = etu_to_clock(etu, FiDi);
	etu_timeout_flag = 0;
	ClockCountor_Start(clock, timeout_action);
}

void ETUTimer_Reset(void)
{
    etu_timeout_flag = 0;
    ClockCountor_Reset();
}

uint32_t ETUTimer_CheckTimeout(void)
{
	//return (etu_timeout_flag == 1) || (etu_alarm_flag == 1);
	return (etu_timeout_flag == 1); 
	//return 0;
}

void  ETUTimer_Stop(void)
{
    ClockCountor_Stop();
    etu_timeout_flag = 0;
}

void ETUTimer_Wait(uint32_t etu, uint8_t FiDi)
{
	ETUTimer_Start(etu, FiDi);
	while(etu_timeout_flag != 1);
	ETUTimer_Stop();
}


void ETUTimer_StartAlarmer(uint32_t etu, uint8_t FiDi)
{
	uint32_t clock;

	etu_alarm_flag = 0;	
	clock = etu_to_clock(etu, FiDi);	
	ClockAlarmer_Start(clock, alarm_action);
}

void ETUTimer_StopAlarmer(void)
{
	ClockAlarmer_Stop();
	etu_alarm_flag = 0;	
}

#if 0

void test_ETUTimer(void)
{
	while(1)
	{
		//GPIO_SetBits(GPIOC, GPIO_Pin_1);
		GPIOC->BSRR = GPIO_Pin_1;
		ClockCountor_Wait(372 * 16);
		//GPIO_ResetBits(GPIOC, GPIO_Pin_1);
		GPIOC->BRR = GPIO_Pin_1;
		ClockCountor_Wait(372 * 16);
	}
}
#endif

